package com.hk.admin.common.util;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <br>
 * <b>功能：</b>ckeditor编辑器工具类<br>
 * <b>作者：</b>Pan.ShiJu<br>
 * <b>日期：</b>2017/4/11 23:27<br>
 */
public class CKEditorUtil {

    private static final String CONTENT_TYPE_TEXT_HTML = "text/html; charset=UTF-8";
    private static final String HEADER_CACHE_CONTROL = "Cache-Control";
    private static final String HEADER_CACHE_CONTROL_NO_CACHE = "no-cache";
    private static final String HEADER_X_FRAME_OPTIONS = "X-Frame-Options";
    private static final String HEADER_X_FRAME_OPTIONS_SAMEORIGIN = "SAMEORIGIN";


    /**
     * ckeditor 上传图片响应头
     *
     * @param response http响应
     */
    public static void setUpCkeditorResponse(HttpServletResponse response) {
        response.setContentType(CONTENT_TYPE_TEXT_HTML);
        response.setHeader(HEADER_CACHE_CONTROL, HEADER_CACHE_CONTROL_NO_CACHE);
        response.setHeader(HEADER_X_FRAME_OPTIONS, HEADER_X_FRAME_OPTIONS_SAMEORIGIN);
    }


    /**
     * ckeditor 响应字符串
     *
     * @param imageUrl 图片的url
     * @param callback ckeditor的特有回调标志
     * @return ckeditor特殊的回调字符串
     */
    public static String getCkeditorResponse(String imageUrl, String callback) {
        return "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" +
                callback +
                ", '" +
                imageUrl +
                "');</script>";
    }


    /**
     * 返回响应流
     *
     * @param response     http响应对象
     * @param responseData 返回前端字符串
     * @throws IOException 可能出现的IO异常
     */
    public static void writerResponse(HttpServletResponse response, String responseData) throws IOException {
        PrintWriter out = response.getWriter();
        out.println(responseData);
        out.flush();
        out.close();
    }

}
